var divRss = document.getElementById('rss');
var divHeapTotal = document.getElementById('heapTotal');
var divHeapUsed = document.getElementById('heapUsed');
var divExternal = document.getElementById('external');

function updateStats(data) {
  divRss.innerHTML = data['rss'];
  divHeapTotal.innerHTML = data['heapTotal'];
  divHeapUsed.innerHTML = data['heapUsed'];
  divExternal.innerHTML = data['external'];
}

var url = window.origin.replace(/^https?:(?=\/\/)/, 'ws:');
var ws = new ReconnectingWebSocket(url);
var count = 0;

ws.onmessage = function (event) {
  const data = JSON.parse(event.data);
  if (data.type === 'usage') {
    updateStats(data.usage);
  }
  switch (data.type) {
    case 'usage':
      updateStats(data.usage);
      break;
    case 'ping':
      ws.send(JSON.stringify({type: 'pong', from: location.host, count: ++count}));
      break;
    default:
      break;
  }
};

setInterval(function () {
  ws.send(JSON.stringify({type: 'usage', from: location.host, count: ++count}));
}, 1000);

setTimeout(function () {
  setInterval(function () {
    ws.send(JSON.stringify({type: 'ping', from: location.host, count: ++count}));
  }, 1000);
}, 500);
